package com.abc.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.abc.constant.PromptConstants;
import com.abc.dto.request.CreateSessionRequestDto;
import com.abc.dto.request.GenerateTitleRequestDto;
import com.abc.dto.response.CreateSessionResponseDto;
import com.abc.dto.response.GenerateTitleResponseDto;
import com.abc.enums.IdType;
import com.abc.enums.PromptType;
import com.abc.help.SessionHelper;
import com.abc.mapper.SessionMapper;
import com.abc.model.SessionModel;
import com.abc.service.IdGeneratorService;
import com.abc.service.SessionService;
import com.abc.util.PromptUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 会话服务实现类
 */
@Slf4j
@Service
public class SessionServiceImpl extends ServiceImpl<SessionMapper, SessionModel> implements SessionService {

    @Autowired
    private IdGeneratorService idGeneratorService;

    @Autowired
    private ChatClient zhipuChatClient;

    @Autowired
    private PromptUtil promptUtil;

    @Override
    public CreateSessionResponseDto createSession(CreateSessionRequestDto requestDto) {
        String sessionId = idGeneratorService.generateId(IdType.SESSION);
        String user = SessionHelper.getUser();
        SessionModel sessionModel = new SessionModel();
        sessionModel.setSessionId(sessionId);
        sessionModel.setUsername(user);
        save(sessionModel);
        CreateSessionResponseDto responseDto = new CreateSessionResponseDto();
        responseDto.setSessionId(sessionId);
        return responseDto;
    }

    @Override
    public GenerateTitleResponseDto generateTitle(GenerateTitleRequestDto requestDto) {
        SessionModel one = getOne(Wrappers.<SessionModel>lambdaQuery().eq(SessionModel::getSessionId, requestDto.getSessionId()).eq(SessionModel::getUsername, SessionHelper.getUser()));
        if (ObjectUtil.isEmpty(one)) {
            throw new IllegalArgumentException("会话已失效");
        }
        String systemPrompt = promptUtil.getSystemPrompt(PromptType.TITLE);
        String userPrompt = promptUtil.getUserPrompt(PromptType.TITLE, requestDto.getUserMessage());

        GenerateTitleResponseDto responseDto = zhipuChatClient.prompt()
                .system(systemPrompt)
                .user(userPrompt)
                .call()
                .responseEntity(GenerateTitleResponseDto.class)
                .getEntity();
        one.setTitle(PromptConstants.DEFAULT_TITLE);

        if (ObjectUtil.isNotEmpty(requestDto) && ObjectUtil.isNotEmpty(responseDto.getTitle())) {
            one.setTitle(responseDto.getTitle());
        }
        updateById(one);
        return responseDto;

    }
}
